//
//  CNM_ExImage.swift
//  swiftTXH
//
//  Created by Mac mini on 2020/12/27.
//  Copyright © 2020 Mac mini. All rights reserved.
//

import UIKit

// MARK: - 加载 Bundle 中得资源
public extension UIImage {
    convenience init?<T: AnyObject>(nameInBundle name: String, bundleName: String, targetClass: T.Type) {
        var path = Bundle(for: T.self).resourcePath ?? ""
        path.append("/\(bundleName).bundle")
        
        let bundle = Bundle(path: path)
        
        self.init(named: name, in: bundle, compatibleWith: nil)
    }
}


// MARK: - 设置圆角
public extension UIImage {
    func cnm_setImageRoundCorner(radius: CGFloat = 8, corners: UIRectCorner = .allCorners, imageSize: CGSize?) -> UIImage? {
        let rsSize = imageSize ?? size
        let rect = CGRect(origin: .zero, size: rsSize)
        // 开启绘制图片上下文和默认设置
        UIGraphicsBeginImageContextWithOptions(rsSize, false, UIScreen.main.scale)
        // 获取当前上下文
        guard let context = UIGraphicsGetCurrentContext() else {
            // 关闭上下文
            UIGraphicsEndImageContext()
            return nil
        }
        
        // 绘制路线
        context.addPath(UIBezierPath(roundedRect: rect, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius)).cgPath)
        // 剪裁
        context.clip()
        // 将原图绘制到图形上下文
        draw(in: rect)
        context.drawPath(using: .fillStroke)
        guard let outputImage = UIGraphicsGetImageFromCurrentImageContext() else {
            // 关闭上下文
            UIGraphicsEndImageContext();
            return nil
        }
        // 关闭上下文
        UIGraphicsEndImageContext();
        
        return outputImage
    }
}

// MARK: - 颜色图片
public extension UIImage {
    func cnm_colorImage(color: UIColor, size: CGSize = CGSize(width: 1.0, height: 1.0)) -> UIImage? {
        let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        
        UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
        let context = UIGraphicsGetCurrentContext()
        context?.setFillColor(color.cgColor)
        context?.fill(rect)
        
        let colorImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return colorImage
    }
}

// MARK: - 压缩图片 -> Data
public extension UIImage {
    func cnm_compressImage() -> Data? {
        let width = self.size.width
        let height = self.size.height
        var updateWidth = width
        var updateHeight = height
        
        let longSide = max(width, height)
        let shortSide = min(width, height)
        
        let scale = shortSide / longSide
    
        // 大小压缩
        if (shortSide < 1080 || longSide < 1080) { // 如果宽高任何一边都小于 1080
            updateWidth = width
            updateHeight = height
        } else { // 如果宽高都大于 1080
            if (width < height) { // 说明短边是宽
                updateWidth = 1080;
                updateHeight = 1080 / scale
            } else { // 说明短边是高
                updateWidth = 1080 / scale
                updateHeight = 1080;
            }
        }
        
        let compressSize = CGSize(width: updateWidth, height: updateHeight)
        
        UIGraphicsBeginImageContext(compressSize)
        self.draw(in: CGRect(x: 0, y: 0, width: compressSize.width, height: compressSize.height))
        
        let compressImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        // 质量压缩 50%
        let data = compressImage?.jpegData(compressionQuality: 0.5)
        
        return data;
    }
}

// MARK: - 二维码
public extension UIImage {
    func cnm_createQRImage(with content: String, size: CGSize, isLogo: Bool = false, logo: UIImage? = nil, logoSize: CGSize = CGSize(width: 45, height: 45)) -> UIImage? {
        let filter = CIFilter(name: "QRCode")
        filter?.setDefaults()
        
        let data = content.data(using: String.Encoding.utf8)
        filter?.setValue(data, forKey: "inputMessage")
        
        // 4、设置二维码的纠错水平，越高纠错水平越高，可以污损的范围越大
        // L: 7% M: 15% Q: 25% H: 30%
        filter?.setValue("H", forKey: "inputCorrectionLevel")
        
        // 5、拿到二维码图片，此时的图片不是很清晰，需要二次加工
        guard let outputImage = filter?.outputImage else { return nil }
        
        
        // 二次加工步骤
        let rect = outputImage.extent.integral
        let scale = min(size.width / rect.width, size.height / rect.height)
        let width = rect.width * scale
        let height = rect.height * scale
    
        // 创建基于GPU的CIContext对象, 性能和效果更好
        let context = CIContext(options: nil)
        // 创建CoreGraphics image
        guard let bitmapImage = context.createCGImage(outputImage, from: rect) else { return nil }
        
        // 创建一个DeviceGray颜色空间
        let cs = CGColorSpaceCreateDeviceGray()
        let bitmapRef = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: cs, bitmapInfo: CGImageAlphaInfo.none.rawValue) //图形上下文，画布
        bitmapRef?.interpolationQuality = CGInterpolationQuality.none //写入质量
        bitmapRef?.scaleBy(x: scale, y: scale) //调整“画布”的缩放
        bitmapRef?.draw(bitmapImage, in: rect) //绘制图片
        
        guard let scaledImage = bitmapRef?.makeImage() else { return nil }
        // 清晰的二维码图片
        let qrImage = UIImage(cgImage: scaledImage)
            
        // 判断是否需要logo
        guard isLogo == true, let logo = logo else { return qrImage }
        var newLogo: UIImage = logo
        if let roundCornerLogo = logo.cnm_setImageRoundCorner(radius: 5, imageSize: logoSize) {
            newLogo = roundCornerLogo
        }
        // 给二维码加 logo 图
        UIGraphicsBeginImageContextWithOptions(qrImage.size, false, UIScreen.main.scale)
        qrImage.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
        
        let waterImgX = (size.width - logoSize.width) * 0.5
        let waterImgY = (size.height - logoSize.height) * 0.5
        
        newLogo.draw(in: CGRect(x: waterImgX, y: waterImgY, width: logoSize.width, height: logoSize.height))
        let newPicture = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return newPicture
    }
}
